/**
 * This is a read-only API for Appalachian.  You can retrieve
 * information about what Appalachian is storing, but you can't
 * append or modify any of it via the API.  Users should use
 * Appalachian themselves to change any OpenID information.
 */

var AppalachianAPI = {};

/**
 * List all OpenIDs that Appalachian knows about.
 */
AppalachianAPI.list = function() {
    var ids = AppalachianDB.listAll();
    return ids;
};

/**
 * Check if an OpenID is within Appalachian's stores.
 */
AppalachianAPI.exists = function(openid) {
    return AppalachianDB.exists(openid);
};

/**
 * Check if an OpenID and its use are within Appalachian's stores.
 */
AppalachianAPI.useExists = function(openid, url) {
    return AppalachianDB.useExists(openid, url);
};

/**
 * Retrieve info about an OpenID (given its internal Appalachian identifier)
 */
AppalachianAPI.getInfo = function(id) {
    return AppalachianDB.getInfo(id);
}

/**
 * Initiate a login; takes a continuation function as login that takes
 * continuation functions as arguments - success and failure
 */
AppalachianAPI.login = function(openid, target, login) {
    // extension finds out it needs to login
    // open target in new tab
    gBrowser.selectedTab = gBrowser.addTab(target);
    var tab = gBrowser.selectedTab;
    // look up openid
    var id = AppalachianDB.getInfoByUrl(openid);
    // get use info
    var use;
    var useid;
    if (AppalachianDB.useExists(id, target)) {
        useid = AppalachianDB.getUseId(id, target);
        use = AppalachianDB.getUse(useid, id);
    }

    var success = function() {
        gBrowser.removeTab(tab);
        // now in verifying state... then what?
    };
    var failure = function() {
        Appalachian.getState().advance(APPALACHIAN_ACTION_ABORT);
        gBrowser.removeTab(tab);
        // application should do its own warnings for failure
    };

    // control is surrendered to calling application when cycle
    // returns to doIdle state

    // the calling application should be able to tell if the user
    // has successfully logged in or not and call continuations
    // appropriately

    AppalachianCommands.apiLogin = function() {login(openid, target, success, failure);};

    // 'fake' the click for a login
    if (use)
        AppalachianCommands.useID(id, use["field"], use["form"]);

    // otherwise, this hasn't ever been used - user's going to
    // have to look at it for how to login
};
